import {useXAgent, XStream,} from "ant-design-x-vue";
import { type BubbleMessageType} from "../types"
import {message} from "ant-design-vue";
import {useStore} from "@/store";
const {storeUser} = useStore()  //从store工厂中取出要指定使用的若干个状态数据
const API_URL = import.meta.env.VITE_API_URL  //大模型RAG的baseUrl

const [ agentMessage ] = useXAgent<BubbleMessageType>({
	request: async ({message}, {onSuccess, onUpdate, onError}) => {
		try {
			const response = await fetch( API_URL + '/proxy/message/chat', {
				method: 'POST',
				headers: {
					//Authorization: `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					"inputs": {'mode': message?.mode||'deepseek-v3',linkNet: message?.linkNet? '1':0},
					response_mode: "streaming",  // 流格式的必须为true
					query: message?.content,
					//user: storeUser.id, //用户id改成中间件从服务端redis中获取
					conversation_id: message?.conversationId||'',
					"files": message?.files||[]
				}),
			});
			if (!response.body) {
				throw new Error('服务器未返回流数据');
			}
			let beginMessage = false
			for await (const chunk of XStream({
				readableStream: response.body,
			})) {
				if (chunk.data) {
					let data = JSON.parse(chunk.data)
					//console.log('stream:',data)
					//文档开始记录任务id 和任务id
					if (data.event === "workflow_started") {
						//console.log(data, data.task_id, 666666666)
						// conversation_id.value = data.conversation_id
						// taskId.value = data.task_id
						onUpdate({event:data.event, content:'', conversationId:data.conversation_id, taskId:data.task_id })
					}
					else if (data.event === 'node_finished') {
						onUpdate({event:data.event, content:'',taskId:data.task_id});
					}
					else if (data.event === "message") {
						// content += data.answer
						// onUpdate({content:content})
						if(!beginMessage){
							beginMessage=true;
							onUpdate({event:"message", content:data.answer, mode:message?.mode||'deepseek-v3'}) //复用字段mode，表示真正的文字推流已经开始
						}else{
							onUpdate({event:"message", content:data.answer})
						}

					}
					else if (data.event === "message_end") {
						// onSuccess({content:content});
						onSuccess({event:"message_end", content:''});
					}
				}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			onError(error);
			onSuccess({content:"服务器繁忙，请稍后再试"})
		} finally {
			//loading.value = false; // 请求完成后关闭加载状态
			//onSuccess({content:"服务器繁忙，请稍后再试"})
		}
	},
});
// const {onRequest } = useXChat({
// 	agent: agentMessage.value,
// })
// 常规聊天用的推流
export const apiAiAgent = agentMessage.value;

const [ villageMessage ] = useXAgent<BubbleMessageType>({
	request: async ({message}, {onSuccess, onUpdate, onError}) => {
		try {
			const response = await fetch( API_URL + '/proxy/message/village', {
				method: 'POST',
				headers: {
					//Authorization: `Bearer ${VILLAGE_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					"inputs": {'mode': message?.mode||''},
					response_mode: "streaming",  // 流格式的必须为true
					query: message?.content,
					//user: storeUser.id, //用户id改成中间件从服务端redis中获取
					conversation_id: message?.conversationId||'',
				}),
			});
			if (!response.body) {
				throw new Error('服务器未返回流数据');
			}
			for await (const chunk of XStream({
				readableStream: response.body,
			})) {
				if (chunk.data) {
					let data = JSON.parse(chunk.data)
					//console.log('stream:',data)
					//文档开始记录任务id 和任务id
					if (data.event === "workflow_started") {
						//console.log(data, data.task_id, 666666666)
						// conversation_id.value = data.conversation_id
						// taskId.value = data.task_id
						onUpdate({event:data.event, content:'', conversationId:data.conversation_id, taskId:data.task_id })
					}
					else if (data.event === 'node_finished') {
						onUpdate({event:data.event, content:'',taskId:data.task_id});
					}
					else if (data.event === "message") {
						onUpdate({event:"message", content:data.answer})

					}
					else if (data.event === "message_end") {
						// onSuccess({content:content});
						onSuccess({event:"message_end", content:''});
					}
				}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			onError(error);
			onSuccess({content:"服务器繁忙，请稍后再试"})
		} finally {
			//loading.value = false; // 请求完成后关闭加载状态
			//onSuccess({content:"服务器繁忙，请稍后再试"})
		}
	},
});
// const {onRequest } = useXChat({
// 	agent: agentMessage.value,
// })
// 常规聊天用的推流
export const apiVillageAgent = villageMessage.value;

// 向ai发起的一般http请求
export const apiAiFetch = {
	//复用发送信息的功能，向模型发送一个空消息（大模型端需要对相应流程作好配置，直接返回一个带有会话id的空信息）
	//当前只有通用AI需要建立历史会话列表，村规助手不需要。
	buildConversationId: async (onSuccess?:(body:any)=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/newChat', {
				method: 'POST',
				headers: {
					//Authorization: `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					"inputs": {'mode': ''},
					//response_mode: "blocking",
					//query: ' ',
					//user: storeUser.id,//用户id改成中间件从服务端redis中获取
					//"files": []
				}),
			});
			if (!response.ok) {
				throw new Error('服务器未返回数据');
			}else{
				const body = await response.json();
				if(onSuccess){	onSuccess(body)	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//阻止推流的继续
	stopMessage: async (source:string, taskId:string, onSuccess?:()=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + `/proxy/stopMsg/${source}/${taskId}`, {
				method: 'POST',
				headers: {
					//Authorization: source==='village'? `Bearer ${VILLAGE_KEY}` : `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					//user: storeUser.id,
				}),
			});
			if (!response.body) {
				throw new Error('服务器未返回数据');
			}else{
				if(onSuccess){	onSuccess()	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	getMessageHistory: async (conversationId:string, onSuccess?:(body:any)=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/msgHistory/chat/'+conversationId, {
				method: 'GET',
				headers: {
					//Authorization: `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
			});
			if (!response.ok) {
				throw new Error('服务器未返回数据');
			}else{
				const body = await response.json();
				if(onSuccess){	onSuccess(body)	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//获取会话列表
	loadConversations: async (source:string, onSuccess?:(body:any)=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/chatHistory/'+source, {
				method: 'GET',
				headers: {
					//Authorization: source==='village'? `Bearer ${VILLAGE_KEY}` : `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
			});
			if (!response.ok) {
				throw new Error('服务器未返回数据');
			}else{
				const body = await response.json();
				if(onSuccess){	onSuccess(body)	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//重命名会话(村规助手不需要，仅用于通用AI助理)
	renameConversation: async (conversationId:string,name:string|undefined, autoBuild:boolean, onSuccess?:()=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/renameChat/'+conversationId, {
				method: 'POST',
				headers: {
					//Authorization: `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					//user: storeUser.id,//用户id改成中间件从服务端redis中获取
					name: name,
					auto_generate:autoBuild,
				}),
			});
			if (!response.body) {
				throw new Error('服务器未返回数据');
			}else{
				if(onSuccess){	onSuccess()	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//删除某次会话
	deleteConversation: async (source:String, conversationId:string, onSuccess?:()=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/deleteChat/'+source+'/'+conversationId, {
				method: 'DELETE',
				headers: {
					//Authorization: source==='village'? `Bearer ${VILLAGE_KEY}` : `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				// body: JSON.stringify({
				// 	user: storeUser.id,
				// }),
			});
			if (!response.body) {
				throw new Error('服务器未返回数据');
			}else{
				if(onSuccess){	onSuccess()	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//获取会话开场白和推荐问题列表
	welcomeInfo: async (source:String, onSuccess?:(body:any)=>void, onError?:(error:any)=>void) => {
		try {
			const response = await fetch( API_URL + '/proxy/welcome/'+source, {
				method: 'GET',
				headers: {
					//Authorization: source==='village'? `Bearer ${VILLAGE_KEY}` : `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
			});
			if (!response.ok) {
				throw new Error('服务器未返回数据');
			}else{
				const body = await response.json();
				if(onSuccess){	onSuccess(body)	}
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//上传语音，服务端转文字后返回
	uploadAudio: async (source:string, blob:Blob, onSuccess?:(body:any)=>void, onError?:(error:any)=>void) => {
		try {
			const formData = new FormData();
			formData.append('file', blob, 'temp.mp3'); // 'recording.wav' 是文件名，可根据需要更改
			//formData.append('user', storeUser.id);
			//formData.append('word_timestamps','disabled');
			const response = await fetch(API_URL + '/proxy/audio-to-text/'+source, { // 替换为你的服务器端点URL
				method: 'POST',
				headers: {
					// Authorization: `Bearer ${API_KEY}`, //todo: api_key在未来要放在服务端中间层中，不能暴露到前端
					//'Access-Control-Allow-Origin': API_URL,
				},
				body: formData,
			});
			if (!response.body) {
				throw new Error('服务器未返回数据');
			}else{
				const body = await response.json();
				if(body.text===undefined){
					if(onError)	onError(body.message);
					throw new Error('服务器端错误：'+ (body.message||body.error) );
				}else{
					if(onSuccess){	onSuccess(body)	}
				}

			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			if(onError)	onError(error);
		}
	},
	//获取朗读文字的语音
	getTextSpeech: async (source:string, messageId?:string, text?:string,) => {
		try {
			const response = await fetch( API_URL + '/proxy/text-to-audio/'+source, {
				method: 'POST',
				headers: {
					//Authorization: `Bearer ${API_KEY}`, //todo: api_key在未来要放在服务端中间层中，不能暴露到前端
					'Content-Type': 'application/json',
					//'Access-Control-Allow-Origin': API_URL,
				},
				body: JSON.stringify({
					// user: storeUser.id,
					message_id: messageId? messageId:undefined,
					text: text? text:undefined,
					voice: storeUser.sex===1? 'sambert-zhiqi-v1':'sambert-zhiming-v1',
					// streaming:true,
				}),
			});
			if (!response.ok) {
				throw new Error('服务器未返回数据');
			}else{
				return response
			}
		} catch (error:any) {
			console.error('错误信息', error);
			message.error(error.message||error||'网络超时，请稍候再试');
			// if(onError)	onError(error);
		}
	},
	// getTextSpeech: async (source:string, messageId?:string, text?:string,) => {
	// 	try {
	// 		console.log(source)
	// 		const response = await fetch(  'https://dev.gxjintu.com:8012/v1/text-to-audio', {
	// 			method: 'POST',
	// 			headers: {
	// 				Authorization: `Bearer app-39fcvpzSObgpU3NOwPZ8L2mJ`, //todo: api_key在未来要放在服务端中间层中，不能暴露到前端
	// 				'Content-Type': 'application/json',
	// 			},
	// 			body: JSON.stringify({
	// 				user: storeUser.id,
	// 				message_id: messageId? messageId:undefined,
	// 				text: text? text:undefined,
	// 				voice: storeUser.sex===1? 'sambert-zhiqi-v1':'sambert-zhiming-v1',
	// 				streaming:true,
	// 			}),
	// 		});
	// 		if (!response.ok) {
	// 			throw new Error('服务器未返回数据');
	// 		}else{
	// 			return response
	// 		}
	// 	} catch (error:any) {
	// 		console.error('错误信息', error);
	// 		message.error(error.message||error||'网络超时，请稍候再试');
	// 		// if(onError)	onError(error);
	// 	}
	// },
}